<?php
declare (strict_types=1);

namespace app\common\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class BusinessVideoApply extends Base
{
    public function business()
    {
        return $this->belongsTo(Business::class, 'business_id', 'id')->field('id,title,contacts,mobile,customer_tel,logo,license,full_address');
    }

    public function getStatusAttr($value)
    {
        switch ($value) {
            case 1:
                return "待审核";
            case 2:
                return "已通过";
            default:
                return "已驳回";
        }
    }

    public static function add($business): array
    {
        parent::startTrans();
        try {
            if($business->video_status == 1){
                return ['code' => -1, 'msg' => '申请上传视频审核中，请勿重复提交申请！'];
            }
            if($business->video_status == 2){
                return ['code' => -1, 'msg' => '申请上传视频已审核通过，请勿重复提交！'];
            }

            parent::create([
                'business_id' => $business->id,
            ]);
            $business->video_status = 1;
            $business->save();
            parent::commit();
            return ['code' => 1, 'msg' => '申请已提交，请耐心等待审核！'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function _save($param, $admin): array
    {
        parent::startTrans();
        try {
            $info = parent::where('id', $param['id'])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '记录不存在'];
            }
            if ($info->getData('status') != 1) {
                return ['code' => -1, 'msg' => '记录已审核，请勿重复审核'];
            }

            $info->reject_msg = $param['reject_msg'];
            $info->status = $param['type'];
            $info->admin_id = $admin->id;
            $info->admin_name = $admin->admin_name;
            $info->audit_time = date("Y-m-d H:i:s");
            $info->save();

            Business::where('id', $info->business_id)->save(['video_status'=>$info->getData('status')]);
            parent::commit();
            return ['code' => 1, 'msg' => '操作成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
